<template>
  <basic-container>
    <avue-crud
      :option="option"
      :table-loading="loading"
      :data="data"
      :search.sync="tableForm"
      :defaults.sync="defaults"
      :page.sync="page"
      :permission="permissionList"
      :before-open="beforeOpen"
      ref="crud"
      @row-update="rowUpdate"
      @row-save="rowSave"
      @row-del="rowDel"
      @search-change="searchChange"
      @search-reset="searchReset"
      @selection-change="selectionChange"
      @current-change="currentChange"
      @size-change="sizeChange"
      @refresh-change="refreshChange"
      @on-load="onLoad"
    >
      <template slot="categoryNameSearch">
        <el-input placeholder="请选择类型" readonly="true" v-model="tableForm.categoryName" style="width: 300px">
          <el-button slot="append" icon="el-icon-search" @click="openCateGoryCommonModal"></el-button>
        </el-input>
      </template>
      <template slot="menuRight">
        <user-table-config :option="option" @confirm="(val) => handleSetUserConfig(val, pageCode)"></user-table-config>
      </template>
      <template slot="menuLeft">
        <el-button type="primary" size="small" icon="el-icon-plus" v-if="permission.equipment_add" @click="addBtn">新 增</el-button>
        <el-button type="danger" size="small" icon="el-icon-delete" plain v-if="permission.equipment_delete" @click="handleDelete">删 除 </el-button>
      </template>
      <template slot-scope="{ row, index }" slot="menu">
        <el-button icon="el-icon-view" size="small" type="text" @click="rowView(row)">详情</el-button>
        <el-button icon="el-icon-edit" size="small" type="text" @click="rowUpdate(row)">编辑</el-button>
        <el-button icon="el-icon-delete" size="small" type="text" @click="$refs.crud.rowDel(row, index)">删除</el-button>
      </template>
    </avue-crud>
    <el-dialog v-dragDirectives ref="dialog" :title="dialogTitle" append-to-body :visible.sync="showDialog" :close-on-click-modal="false" top="5vh" @close="closeDialog">
      <div class="sail-header-dialog-content">
        <avue-form ref="basicInfoForm" v-if="showDialog" v-model="form" :option="dialogOption"></avue-form>
        <el-tabs type="border-card" v-if="showDialog" v-model="tabsIndex">
          <el-tab-pane label="专业信息" name="1">
            <avue-form ref="majorInfoForm" v-model="form" :option="majorInfoOption">
              <template slot="principalName">
                <el-input placeholder="请选择 负责人员" v-model="form.principalName" class="input-with-select" disabled>
                  <el-button
                    slot="append"
                    icon="el-icon-circle-close"
                    v-if="form.principalName"
                    :disabled="isDisabled"
                    @click="
                      form.principalName = '';
                      form.principal = '';
                    "
                  ></el-button>
                  <el-button slot="append" icon="el-icon-search" @click="openPrincipalCommonModal()" :disabled="isDisabled"></el-button>
                </el-input>
              </template>
              <template slot="workshopName">
                <el-input placeholder="请选择 所在车间" v-model="form.workshopName" class="input-with-select" disabled>
                  <el-button
                    slot="append"
                    icon="el-icon-circle-close"
                    v-if="form.workshopName"
                    :disabled="isDisabled"
                    @click="
                      form.workshopName = '';
                      form.workshopId = '';
                    "
                  ></el-button>
                  <el-button slot="append" icon="el-icon-search" @click="openWorkshopCommonModal()" :disabled="isDisabled"></el-button>
                </el-input>
              </template>
              <template slot="lineName">
                <el-input placeholder="请选择 所在产线" v-model="form.lineName" class="input-with-select" disabled>
                  <el-button
                    slot="append"
                    icon="el-icon-circle-close"
                    v-if="form.lineName"
                    :disabled="isDisabled"
                    @click="
                      form.lineName = '';
                      form.lineId = '';
                    "
                  ></el-button>
                  <el-button slot="append" icon="el-icon-search" @click="openLineCommonModal()" :disabled="isDisabled"></el-button>
                </el-input>
              </template>
            </avue-form>
          </el-tab-pane>
          <el-tab-pane label="购置信息" name="2">
            <avue-form ref="purchaseInfoForm" v-model="form" :option="purchaseInfoOption">
              <template slot="supplierName">
                <el-input placeholder="请选择 供应商" v-model="form.supplierName" class="input-with-select" disabled>
                  <el-button
                    slot="append"
                    icon="el-icon-circle-close"
                    v-if="form.supplierName"
                    :disabled="isDisabled"
                    @click="
                      form.supplierName = '';
                      form.partnerId = '';
                    "
                  ></el-button>
                  <el-button slot="append" icon="el-icon-search" @click="openVendorCommonModal()" :disabled="isDisabled"></el-button>
                </el-input>
              </template>
            </avue-form>
          </el-tab-pane>
          <el-tab-pane label="附件信息" name="3">
            <avue-form ref="enclosureInfo" v-model="form" :option="enclosureInfoOption">
              <template slot="PICTURE">
                <div v-if="dialogTitle != '详情' && form.PICTURE">
                  <el-upload
                    class="upload-demo"
                    action="/api/blade-resource/oss/endpoint/put-file-attach"
                    list-type="picture"
                    accept="image/png, image/jpeg, image/jpg"
                    :on-change="changeFile"
                    :headers="headersObj"
                    :on-preview="handlePreview"
                    :before-upload="pictureUploadBefore"
                    :on-success="pictureUploadSuccess"
                    :file-list="pictureList"
                  >
                    <el-button size="small" type="primary">点击上传</el-button>
                    <div slot="tip" class="el-upload__tip">只能上传png/jpeg/jpg文件</div>
                  </el-upload>
                </div>
                <div v-if="dialogTitle === '详情' && JSON.stringify(form.PICTURE) != '[]'">
                  <el-image style="width: 100px; height: 100px; padding-right: 10px; display: block" :src="form.PICTURE" @click="openPreview(0, form.PICTURE)"></el-image>
                  <el-button type="text" icon="el-icon-download" size="small" @click="handleDownload(form.PICTURE)">下载</el-button>
                </div>
              </template>
              <template slot="INSPECTION">
                <div v-if="dialogTitle != '详情' && form.INSPECTION">
                  <el-upload
                    class="upload-demo"
                    action="/api/blade-resource/oss/endpoint/put-file-attach"
                    list-type="text"
                    accept=".doc,.docx,.pdf"
                    :on-change="changeFile"
                    :headers="headersObj"
                    :before-upload="textUploadBefore"
                    :on-success="inspectionUploadSuccess"
                    :file-list="inspectionList"
                  >
                    <el-button size="small" type="primary">点击上传</el-button>
                    <div slot="tip" class="el-upload__tip">只能上传doc/docx/pdf文件</div>
                  </el-upload>
                </div>
                <div v-if="dialogTitle === '详情' && JSON.stringify(form.INSPECTION) != '[]'">
                  <div>{{ form.INSPECTIONNAME }}</div>
                  <el-button type="text" icon="el-icon-download" size="small" @click="handleDownload(form.INSPECTION)">下载</el-button>
                </div>
              </template>
              <template slot="CERT">
                <div v-if="dialogTitle != '详情' && form.CERT">
                  <el-upload
                    class="upload-demo"
                    action="/api/blade-resource/oss/endpoint/put-file-attach"
                    list-type="text"
                    accept=".doc,.docx,.pdf"
                    :on-change="changeFile"
                    :headers="headersObj"
                    :before-upload="textUploadBefore"
                    :on-success="certUploadSuccess"
                    :file-list="certList"
                  >
                    <el-button size="small" type="primary">点击上传</el-button>
                    <div slot="tip" class="el-upload__tip">只能上传doc/docx/pdf文件</div>
                  </el-upload>
                </div>
                <div v-if="dialogTitle === '详情' && JSON.stringify(form.CERT) != '[]'">
                  <div>{{ form.CERTNAME }}</div>
                  <el-button type="text" icon="el-icon-download" size="small" @click="handleDownload(form.CERT)">下载</el-button>
                </div>
              </template>
            </avue-form>
          </el-tab-pane>
          <el-tab-pane label="维保信息" name="4">
            <avue-form ref="maintenanceInfo" v-model="form" :option="maintenanceInfoOption">
              <template slot="qcTemplateName">
                <el-input placeholder="请选择 养护检验模版" v-model="form.qcTemplateName" class="input-with-select" disabled>
                  <el-button
                    slot="append"
                    icon="el-icon-circle-close"
                    v-if="form.qcTemplateName"
                    :disabled="isDisabled"
                    @click="
                      form.qcTemplateName = '';
                      form.qcTemplateId = '';
                    "
                  ></el-button>
                  <el-button slot="append" icon="el-icon-search" @click="openQcTemplateModal()" :disabled="isDisabled"></el-button>
                </el-input>
              </template>
            </avue-form>
          </el-tab-pane>
        </el-tabs>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button v-if="dialogTitle === '新增'" type="primary" size="small" @click="submit"> <i class="el-icon-circle-plus-outline"></i><span>保 存</span> </el-button>
        <el-button v-if="dialogTitle === '编辑'" type="primary" size="small" @click="submit"> <i class="el-icon-circle-check"></i><span>修 改</span> </el-button>
        <el-button size="small" @click="showDialog = false"><i class="el-icon-circle-close"></i><span>取 消</span></el-button>
      </span>
    </el-dialog>
    <common-modal-template ref="commonModalTemplate" :option="tableOption" @getSelectedRows="getSelectedRows" :key="timer" @newKey="newKey"> </common-modal-template>
  </basic-container>
</template>
<script>
import { getEquipmentList, getDetail, add, remove } from '@/api/admin/equipment';
import { mapGetters } from 'vuex';
import CommonModalTemplate from '@/components/common-modal-template/common-modal-template.vue';
import website from '@/config/website';
import { Base64 } from 'js-base64';
import { getToken } from '@/util/auth';
import userTableConfig from '@/components/user-table-config';
import userConfig from '@/mixins/userConfig';
export default {
  name: 'EquipmentManageEquipment',
  components: {
    CommonModalTemplate,
    userTableConfig
  },
  mixins: [userConfig()],
  data() {
    return {
      pageCode: 'EQUIPMENT',
      form: {},
      tableForm: {},
      defaults: {},
      query: {},
      loading: true,
      page: {
        pageSize: 20,
        currentPage: 1,
        total: 0
      },
      selectionList: [],
      option: {
        height: 'calc(100vh - 440px)',
        calcHeight: 30,
        tip: false,
        searchShow: true,
        searchMenuSpan: 6,
        border: true,
        index: true,
        indexLabel: '序号',
        addBtn: false,
        viewBtn: false,
        editBtn: false,
        delBtn: false,
        selection: true,
        menuWidth: 200, //弹框内字段宽度属性
        dialogWidth: 880, //弹框宽度属性
        labelWidth: '110',
        dialogClickModal: false,
        columnBtn: false,
        column: [
          {
            label: '编码',
            prop: 'code',
            search: true,
            rules: [
              {
                required: true,
                message: '请输入编码',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '名称',
            prop: 'name',
            search: true,
            rules: [
              {
                required: true,
                message: '请输入名称',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '类型',
            prop: 'categoryName',
            search: true,
            searchType: 'search',
            formslot: true
          },
          // {
          //   label: '类型',
          //   prop: 'categoryName'
          // },
          {
            label: '型号',
            prop: 'model'
          },
          {
            label: '规格',
            prop: 'specification',
            rules: [
              {
                required: false,
                message: '请输入规格描述',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '状态',
            prop: 'statusValue'
          }
        ]
      },
      dialogTitle: '新增',
      showDialog: false,
      dialogOption: {
        submitBtn: false,
        emptyBtn: false,
        labelWidth: '130',
        column: [
          {
            label: '编码',
            prop: 'code',
            rules: [
              {
                required: true,
                message: '请输入编码',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '名称',
            prop: 'name',
            rules: [
              {
                required: true,
                message: '请输入名称',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '类型',
            prop: 'categoryName',
            search: true,
            type: 'search',
            disabled: true,
            placeholder: '请选择 类型',
            appendClick: () => {
              if (this.dialogTitle === '详情') return;
              this.openCateGoryCommonModal();
            },
            rules: [
              {
                required: true,
                message: '请选择类型',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '状态',
            prop: 'status',
            type: 'select',
            dicUrl: '/api/blade-system/dict/dictionary?code=tooling_fixture_status',
            props: {
              label: 'dictValue',
              value: 'dictKey'
            },
            rules: [
              {
                required: true,
                message: '请选择状态',
                trigger: 'blur'
              }
            ]
          },
          {
            label: '品牌',
            prop: 'brand',
            rules: [
              {
                required: true,
                message: '请输入品牌',
                trigger: 'blur'
              }
            ]
          }
        ]
      },
      tabsIndex: '1',
      majorInfoOption: {
        submitBtn: false,
        emptyBtn: false,
        labelWidth: '130',
        column: [
          {
            label: '负责部门',
            prop: 'principalDeptId',
            type: 'tree',
            dicUrl: '/api/blade-system/dept/tree?tenantId=',
            props: {
              label: 'title'
            },
            checkStrictly: true
          },
          {
            label: '负责人员',
            prop: 'principalName'
          },
          {
            label: '所在车间',
            prop: 'workshopName'
          },
          {
            label: '所在产线',
            prop: 'lineName'
          },
          {
            label: '设备来源',
            prop: 'assetFrom',
            type: 'select',
            dicUrl: '/api/blade-system/dict/dictionary?code=equipment_sources',
            props: {
              label: 'dictValue',
              value: 'dictKey'
            }
          },
          {
            label: '规格',
            prop: 'specification'
          },
          {
            label: '型号',
            prop: 'model'
          },
          {
            label: 'IP地址',
            prop: 'ip',
            rules: [
              {
                required: false,
                trigger: 'blur',
                validator: (rule, value, callback) => {
                  if (value) {
                    let result = this.getValidResult('ip', value);
                    if (result) {
                      callback();
                    } else {
                      callback(new Error('请输入正确的IP地址'));
                    }
                  } else {
                    callback();
                  }
                }
              }
            ]
          },
          {
            label: '端口',
            prop: 'port',
            rules: [
              {
                required: false,
                trigger: 'blur',
                validator: (rule, value, callback) => {
                  if (value) {
                    let result = this.getValidResult('port', value);
                    if (result) {
                      callback();
                    } else {
                      callback(new Error('请输入正确的端口号'));
                    }
                  } else {
                    callback();
                  }
                }
              }
            ]
          },
          {
            label: '主机名称',
            prop: 'hostName'
          },
          {
            label: '网络协议类型',
            prop: 'protocol',
            type: 'select',
            dicUrl: '/api/blade-system/dict/dictionary?code=protocol',
            props: {
              label: 'dictValue',
              value: 'dictKey'
            }
          },
          {
            label: '标准工时',
            prop: 'standardOperatingHours',
            type: 'number',
            minRows: 0,
            value: 8
          },
          {
            label: '备注',
            prop: 'remarks',
            hide: true,
            type: 'textarea',
            minRows: 3,
            maxRows: 3
          }
        ]
      },
      purchaseInfoOption: {
        submitBtn: false,
        emptyBtn: false,
        labelWidth: '130',
        column: [
          {
            label: '资产编码',
            prop: 'assetCode'
          },
          {
            label: '购置价格',
            prop: 'procurementPrice',
            rules: [
              {
                required: false,
                trigger: 'blur',
                validator: (rule, value, callback) => {
                  let reg = /^((0{1}\.\d{1,4})|([0-9]\d*\.{1}\d{1,4})|([0-9]+\d*))$/g;
                  if (value && !reg.test(value)) {
                    callback(new Error('购置价格为数字，不能小于0，可保留4位小数'));
                  } else {
                    callback();
                  }
                }
              }
            ]
          },
          {
            label: '购置日期',
            prop: 'procurementDate',
            type: 'datetime',
            format: 'yyyy-MM-dd HH:mm:ss',
            valueFormat: 'yyyy-MM-dd HH:mm:ss'
          },
          {
            label: '供应商',
            prop: 'supplierName'
          },
          {
            label: '资产类别',
            prop: 'assetType',
            type: 'select',
            dicUrl: '/api/blade-system/dict/dictionary?code=asset_classes',
            props: {
              label: 'dictValue',
              value: 'dictKey'
            }
          },
          {
            label: '出厂日期',
            prop: 'manufactureDate',
            type: 'datetime',
            format: 'yyyy-MM-dd HH:mm:ss',
            valueFormat: 'yyyy-MM-dd HH:mm:ss'
          },
          {
            label: '入账日期',
            prop: 'keepAccountDate',
            type: 'datetime',
            format: 'yyyy-MM-dd HH:mm:ss',
            valueFormat: 'yyyy-MM-dd HH:mm:ss'
          },
          {
            label: '启用日期',
            prop: 'enabledDate',
            type: 'datetime',
            format: 'yyyy-MM-dd HH:mm:ss',
            valueFormat: 'yyyy-MM-dd HH:mm:ss'
          },
          {
            label: '预计使用年限',
            prop: 'expectedLife',
            rules: [
              {
                required: false,
                trigger: 'blur',
                validator: (rule, value, callback) => {
                  let reg = /^((0{1}\.\d{1,2})|([1-9]\d*\.{1}\d{1,2})|([1-9]+\d*))$/g;
                  if (value && !reg.test(value)) {
                    callback(new Error('预计使用年限为数字，不能小于等于0，可保留2位小数'));
                  } else {
                    callback();
                  }
                }
              }
            ]
          }
        ]
      },
      enclosureInfoOption: {
        submitBtn: false,
        emptyBtn: false,
        labelWidth: '130',
        column: [
          {
            label: '设备图片',
            prop: 'PICTURE',
            type: 'upload'
          },
          {
            label: '验收报告附件',
            prop: 'INSPECTION',
            type: 'upload'
          },
          {
            label: '投产验证附件',
            prop: 'CERT',
            type: 'upload'
          }
        ]
      },
      maintenanceInfoOption: {
        submitBtn: false,
        emptyBtn: false,
        labelWidth: '130',
        column: [
          {
            label: '养护检验模版',
            prop: 'qcTemplateName'
          },
          {
            label: '上次养护时间',
            prop: 'latestMaintain',
            type: 'datetime',
            format: 'yyyy-MM-dd HH:mm:ss',
            valueFormat: 'yyyy-MM-dd HH:mm:ss',
            disabled: true
          }
        ]
      },
      timer: new Date().getTime(), //不同内容使用同一个模态框结构，key值不同需要重新请求渲染数据，否则会请求到上一个使用的数据内容
      modalName: '', //打开公用模态框名称
      tableOption: {}, //公用模态框配置信息
      data: [],
      pictureList: [],
      inspectionList: [],
      certList: []
    };
  },
  mounted() {
    this.$nextTick(() => {
      this.$structuralSplit();
    });
  },
  computed: {
    ...mapGetters(['permission']),
    permissionList() {
      return {
        addBtn: this.vaildData(this.permission.equipment_add, false),
        viewBtn: this.vaildData(this.permission.equipment_view, false),
        delBtn: this.vaildData(this.permission.equipment_delete, false),
        editBtn: this.vaildData(this.permission.equipment_edit, false)
      };
    },
    ids() {
      let ids = [];
      this.selectionList.forEach((ele) => {
        ids.push(ele.id);
      });
      return ids;
    },
    headersObj() {
      let header = { Authorization: `Basic ${Base64.encode(`${website.clientId}:${website.clientSecret}`)}` };
      header['Blade-Auth'] = 'bearer ' + getToken();
      return header;
    },
    isDisabled() {
      return this.dialogTitle === '详情';
    }
  },
  methods: {
    /**
     * 重新加载公用表格弹窗组件
     */
    newKey() {
      this.timer = new Date().getTime();
    },
    getValidResult(label, value) {
      switch (label) {
        case 'ip':
          let arr = value.split('.');
          arr[0] = Number(arr[0]);
          arr[1] = Number(arr[1]);
          arr[2] = Number(arr[2]);
          arr[3] = Number(arr[3]);
          if (arr.length < 4 || arr.length > 4) {
            return false;
          } else {
            let reg = /^(0|\+?[1-9][0-9]*)$/;
            if (reg.test(arr[0]) && reg.test(arr[1]) && reg.test(arr[2]) && reg.test(arr[3])) {
              if (arr[0] > 255 || arr[1] > 255 || arr[2] > 255 || arr[3] > 255) {
                return false;
              } else {
                return true;
              }
            } else {
              return false;
            }
          }
        case 'port':
          let reg = /^(0|\+?[1-9][0-9]*)$/;
          if (reg.test(Number(value))) {
            if (Number(value) > 65535) {
              return false;
            } else {
              return true;
            }
          } else {
            return false;
          }
      }
    },
    handleDelete() {
      if (this.selectionList.length === 0) {
        this.$message.warning('请选择至少一条数据');
        return;
      }
      this.$confirm('确定将选择数据删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          return remove(this.ids);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
          this.$refs.crud.toggleSelection();
        });
    },
    searchReset() {
      this.tableForm = {};
      this.query = {};
      this.onLoad(this.page);
    },
    searchChange(params, done) {
      this.page.currentPage = 1;
      this.onLoad(this.page, params);
      done();
    },
    selectionChange(list) {
      this.selectionList = list;
    },
    selectionClear() {
      this.selectionList = [];
      this.$refs.crud.toggleSelection();
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    refreshChange() {
      this.onLoad(this.page, this.query);
    },
    onLoad(page, params = {}) {
      this.loading = true;
      getEquipmentList(page.currentPage, page.pageSize, Object.assign(params, this.query)).then((res) => {
        const data = res.data.data;
        this.page.total = data.total;
        this.data = data.records;
        this.loading = false;
        this.selectionClear();
      });
    },
    addBtn() {
      this.showDialog = true;
      this.dialogTitle = '新增';
      this.$nextTick(() => {
        this.$refs.basicInfoForm.allDisabled = false;
        this.$refs.majorInfoForm.allDisabled = false;
        this.$refs.purchaseInfoForm.allDisabled = false;
        this.$refs.enclosureInfo.allDisabled = false;
        this.$refs.maintenanceInfo.allDisabled = false;
      });
      this.form['equipmentAttachmentList'] = [];
    },
    openCateGoryCommonModal() {
      this.modalName = 'cateGoryModal';
      this.$refs.commonModalTemplate.showModal();
      this.tableOption = {
        modalTitle: '选择设备类别信息（双击进行选择）',
        url: '/api/mes-product/ems-equipment-category/page',
        isPage: true,
        rowSelectionType: 'single',
        columnDefs: [
          {
            label: '编码',
            prop: 'code',
            search: true
          },
          {
            label: '名称',
            prop: 'name',
            search: true
          }
        ]
      };
    },
    openPrincipalCommonModal() {
      this.modalName = 'principalModal';
      this.$refs.commonModalTemplate.showModal();
      this.tableOption = {
        modalTitle: '选择用户管理信息（双击进行选择）',
        url: '/api/blade-system/user/page',
        isPage: true,
        rowSelectionType: 'single',
        columnDefs: [
          {
            label: '用户姓名',
            prop: 'realName',
            search: true,
            searchLabelWidth: 150,
            searchSpan: 8
          },
          {
            label: '所属部门',
            prop: 'deptName',
            searchLabelWidth: 150,
            searchSpan: 8
          },
          {
            label: '职务',
            prop: 'postName'
          },
          {
            label: '用户平台',
            prop: 'userTypeName'
          }
        ]
      };
    },
    openWorkshopCommonModal() {
      this.modalName = 'workshopModal';
      this.$refs.commonModalTemplate.showModal();
      this.tableOption = {
        modalTitle: '选择车间信息（双击进行选择）',
        url: '/api/mes-admin/workshop/page',
        isPage: true,
        rowSelectionType: 'single',
        columnDefs: [
          {
            label: '车间编码',
            prop: 'code',
            search: true
          },
          {
            label: '车间名称',
            prop: 'name',
            search: true
          }
        ]
      };
    },
    /**
     * 打开产线选择模态框
     */
    openLineCommonModal() {
      this.modalName = 'lineModal';
      this.$refs.commonModalTemplate.showModal();
      let url = '';
      if (this.form.workshopId) {
        url = `/api/mes-product/productionline/page?workshopId=${this.form.workshopId}`;
      } else {
        url = '/api/mes-product/productionline/page';
      }
      this.tableOption = {
        modalTitle: '选择产线信息（双击进行选择）',
        url: url,
        isPage: true,
        rowSelectionType: 'single',
        menu: false,
        editBtn: false,
        menuWidth: 100,
        columnDefs: [
          {
            label: '产线名称',
            prop: 'name',
            search: true
          },
          {
            label: '产线编码',
            prop: 'code',
            search: true
          }
        ]
      };
    },
    /**
     * 打开供应商选择模态框
     */
    openVendorCommonModal() {
      this.modalName = 'vendorModal';
      this.$refs.commonModalTemplate.showModal();
      this.tableOption = {
        modalTitle: '选择供应商信息（双击进行选择）',
        url: '/api/mes-admin/vendor/page',
        isPage: true,
        rowSelectionType: 'single',
        menu: false,
        editBtn: false,
        menuWidth: 100,
        columnDefs: [
          {
            label: '编码',
            prop: 'code',
            search: true
          },
          {
            label: '名称',
            prop: 'name',
            search: true
          }
        ]
      };
    },
    /**
     * 打开养护检验模态框
     */
    openQcTemplateModal() {
      this.modalName = 'qcTemplateModal';
      this.$refs.commonModalTemplate.showModal();
      this.tableOption = {
        modalTitle: '选择养护检验模版信息（双击进行选择）',
        url: '/api/mes-product/qms-inspection-template/page?status=1&type=MI',
        isPage: true,
        rowSelectionType: 'single',
        menu: false,
        editBtn: false,
        menuWidth: 100,
        searchSpan: 8,
        searchLabelWidth: 130,
        columnDefs: [
          {
            label: '检验模板名称',
            prop: 'name',
            search: true
          },
          {
            label: '检验模板编码',
            prop: 'code'
          },
          {
            label: '版本号',
            prop: 'revision'
          }
        ]
      };
    },
    /**
     * 获取选择的模态框行数据
     */
    getSelectedRows(rowData) {
      switch (this.modalName) {
        case 'cateGoryModal':
          if (!this.showDialog) {
            this.tableForm.categoryName = this._get(rowData, 'name', '');
            this.tableForm.categoryId = this._get(rowData, 'id', '');
            this.query.categoryId = this._get(rowData, 'id', '');
            this.query.categoryName = this._get(rowData, 'name', '');
          } else {
            this.form.categoryId = this._get(rowData, 'id', '');
            this.form.categoryName = this._get(rowData, 'name', '');
          }
          break;
        case 'principalModal':
          this.form.principal = this._get(rowData, 'id', '');
          this.form.principalName = this._get(rowData, 'realName', '');
          break;
        case 'workshopModal':
          this.form.workshopId = this._get(rowData, 'id', '');
          this.form.workshopName = this._get(rowData, 'name', '');
          break;
        case 'lineModal':
          this.form.lineId = this._get(rowData, 'id', '');
          this.form.lineName = this._get(rowData, 'name', '');
          break;
        case 'vendorModal':
          this.form.partnerId = this._get(rowData, 'id', '');
          this.form.supplierName = this._get(rowData, 'name', '');
          break;
        case 'qcTemplateModal':
          this.form.qcTemplateId = this._get(rowData, 'id', '');
          this.form.qcTemplateName = this._get(rowData, 'name', '');
          break;
        default:
          break;
      }
    },
    /**
     * 上传前方法
     */
    pictureUploadBefore(file) {
      console.log(file);
      if (file.name.split('.')[1] != 'png' && file.name.split('.')[1] != 'jpeg' && file.name.split('.')[1] != 'jpg') {
        this.$message({
          type: 'warning',
          message: '只能上传png/jpeg/jpg文件！'
        });
        return false;
      }
    },
    textUploadBefore(file) {
      if (file.name.split('.')[1] != 'doc' && file.name.split('.')[1] != 'docx' && file.name.split('.')[1] != 'pdf') {
        this.$message({
          type: 'warning',
          message: '只能上传dox/docx/pdf文件！'
        });
        return false;
      }
    },
    pictureUploadSuccess(res) {
      if (this.form.equipmentAttachmentList) {
        for (let i = 0; i < this.form.equipmentAttachmentList.length; i++) {
          if ('PICTURE' === this.form.equipmentAttachmentList[i].attachmentType) {
            this.form.equipmentAttachmentList.splice(i, 1);
          }
        }
      } else {
        this.form.equipmentAttachmentList = [];
      }
      this.form.PICTURE = res.data.link;
      this.form['equipmentAttachmentList'].push({
        attachmentId: res.data.attachId,
        link: res.data.link,
        originalName: res.data.originalName,
        attachmentType: 'PICTURE'
      });
    },
    inspectionUploadSuccess(res) {
      if (this.form.equipmentAttachmentList) {
        for (let i = 0; i < this.form.equipmentAttachmentList.length; i++) {
          if ('INSPECTION' === this.form.equipmentAttachmentList[i].attachmentType) {
            this.form.equipmentAttachmentList.splice(i, 1);
          }
        }
      } else {
        this.form.equipmentAttachmentList = [];
      }
      this.form.INSPECTION = res.data.link;
      this.form['equipmentAttachmentList'].push({
        attachmentId: res.data.attachId,
        link: res.data.link,
        originalName: res.data.originalName,
        attachmentType: 'INSPECTION'
      });
    },
    certUploadSuccess(res) {
      if (this.form.equipmentAttachmentList) {
        for (let i = 0; i < this.form.equipmentAttachmentList.length; i++) {
          if ('CERT' === this.form.equipmentAttachmentList[i].attachmentType) {
            this.form.equipmentAttachmentList.splice(i, 1);
          }
        }
      } else {
        this.form.equipmentAttachmentList = [];
      }
      this.form.CERT = res.data.link;
      this.form['equipmentAttachmentList'].push({
        attachmentId: res.data.attachId,
        link: res.data.link,
        originalName: res.data.originalName,
        attachmentType: 'CERT'
      });
    },

    changeFile(files, fileList) {
      if (fileList.length > 1) {
        fileList.splice(0, 1);
      }
    },
    // /**
    //  * 删除上传文件
    //  */
    // uploadDelete(file, column) {
    //   for (let i = 0; i < this.form.equipmentAttachmentList.length; i++) {
    //     if (column.prop === this.form.equipmentAttachmentList[i].attachmentType) {
    //       this.form.equipmentAttachmentList.splice(i, 1);
    //       this.form[column.prop] = '';
    //       // return;
    //     }
    //   }
    // },
    /**
     * 提交
     */
    async submit() {
      let validData1 = await new Promise((resolve, reject) => {
        this.$refs.basicInfoForm.validate((valid, done) => {
          if (valid) {
            resolve();
            done();
          }
        });
      });
      let validData2 = await new Promise((resolve, reject) => {
        this.$refs.majorInfoForm.validate((valid, done) => {
          if (valid) {
            resolve();
            done();
          } else {
            this.tabsIndex = '1';
          }
        });
      });
      let validData3 = new Promise((resolve, reject) => {
        this.$refs.purchaseInfoForm.validate((valid, done) => {
          if (valid) {
            resolve();
            done();
          } else {
            this.tabsIndex = '2';
          }
        });
      });
      Promise.all([validData1, validData2, validData3]).then(() => {
        delete this.form.PICTURE;
        delete this.form.INSPECTION;
        delete this.form.CERT;
        this.form.categoryType = 'EQUIPMENT_LEDGER';
        this.form.equipmentTool = {
          procurementPrice: this.form.procurementPrice,
          partnerId: this.form.partnerId,
          keepAccountDate: this.form.keepAccountDate,
          enabledDate: this.form.enabledDate
        };
        add(this.form).then((res) => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: res.data.msg
          });
          this.showDialog = false;
        });
      });
    },
    /**
     * 查看详情数据
     */
    rowView(row) {
      this.showDialog = true;
      this.dialogTitle = '详情';
      this.$nextTick(() => {
        this.$refs.basicInfoForm.allDisabled = true;
        this.$refs.majorInfoForm.allDisabled = true;
        this.$refs.purchaseInfoForm.allDisabled = true;
        this.$refs.enclosureInfo.allDisabled = true;
        this.$refs.maintenanceInfo.allDisabled = true;
      });
      getDetail(row.id).then((res) => {
        this.form = res.data.data;
        this.form.status = this.form.status.toString();
        this.form.keepAccountDate = this._get(res, 'data.data.equipmentTool.keepAccountDate', '');
        this.form.enabledDate = this._get(res, 'data.data.equipmentTool.enabledDate', '');
        this.form.partnerId = this._get(res, 'data.data.equipmentTool.partnerId', '');
        this.form.supplierName = this._get(res, 'data.data.equipmentTool.supplierName', '');
        this.form.procurementPrice = this._get(res, 'data.data.equipmentTool.procurementPrice', '');
        this._forEach(this.form.equipmentAttachmentList, (item) => {
          if (item.attachmentType === 'PICTURE') {
            this.form.PICTURE = item.link;
          } else if (item.attachmentType === 'INSPECTION') {
            this.form.INSPECTION = item.link;
            this.form.INSPECTIONNAME = item.originalName;
          } else if (item.attachmentType === 'CERT') {
            this.form.CERT = item.link;
            this.form.CERTNAME = item.originalName;
          }
        });
      });
    },
    rowUpdate(row) {
      this.showDialog = true;
      this.dialogTitle = '编辑';
      this.$nextTick(() => {
        this.$refs.basicInfoForm.allDisabled = false;
        this.$refs.majorInfoForm.allDisabled = false;
        this.$refs.purchaseInfoForm.allDisabled = false;
        this.$refs.enclosureInfo.allDisabled = false;
        this.$refs.maintenanceInfo.allDisabled = false;
      });
      getDetail(row.id).then((res) => {
        this.form = res.data.data;
        this.form.status = this.form.status.toString();
        this.form.keepAccountDate = this._get(res, 'data.data.equipmentTool.keepAccountDate', '');
        this.form.enabledDate = this._get(res, 'data.data.equipmentTool.enabledDate', '');
        this.form.partnerId = this._get(res, 'data.data.equipmentTool.partnerId', '');
        this.form.supplierName = this._get(res, 'data.data.equipmentTool.supplierName', '');
        this.form.procurementPrice = this._get(res, 'data.data.equipmentTool.procurementPrice', '');
        this._forEach(this.form.equipmentAttachmentList, (item) => {
          if (item.attachmentType === 'PICTURE') {
            this.pictureList = [{ name: item.originalName, url: item.link }];
          } else if (item.attachmentType === 'INSPECTION') {
            this.inspectionList = [{ name: item.originalName, url: item.link }];
          } else if (item.attachmentType === 'CERT') {
            this.certList = [{ name: item.originalName, url: item.link }];
          }
        });
      });
    },
    rowDel(row) {
      this.$confirm('确定将选择数据删除?', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(() => {
          return remove([row.id]);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: 'success',
            message: '操作成功!'
          });
        });
    },
    closeDialog() {
      this.$refs.basicInfoForm.resetFields();
      this.$refs.majorInfoForm.resetFields();
      this.$refs.purchaseInfoForm.resetFields();
      this.$refs.enclosureInfo.resetFields();
      this.$refs.maintenanceInfo.resetFields();
      this.form = {};
      this.pictureList = [];
      this.inspectionList = [];
      this.certList = [];
      this.tabsIndex = '1';
    },
    handleDownload(link) {
      window.open(`${link}`);
    },
    openPreview(index = 0, link) {
      this.$ImagePreview([{ url: link }], index, {
        closeOnClickModal: false
      });
    },
    handlePreview(file) {
      let url = this._get(file, 'response.data.link', '');
      this.$ImagePreview([{ url: url }], 0, {
        closeOnClickModal: false
      });
    }
  }
};
</script>
